package com.smforj.ssm.mina.client;  
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.smforj.ssm.mina.codec.MsgCodecFactory;
import com.smforj.ssm.mina.codec.MsgEntity;

/**
 * mina 客户端对象
 * @desp
 * @author ghj
 * @date 2016-3-8 下午6:20:02
 */
public class MinaClient implements IMinaClent{ 
	/**
	 * 
	 */
    private String sHost = "localhost";  
    private int sPort = 6789;  
    static long counter = 0;  
    final static int FC1 = 10;  
    static long start = 0; 
    
    
    private IoConnector connector; 
    private ConnectFuture connFuture; 
    private IoSession session; 
    private CloseFuture cfuture;
    /** 
     * 使用Mina的框架结构进行测试 
     *  
     * @param args 
     * @throws InterruptedException 
     */  
    public static void main(String[] args) throws IOException, InterruptedException {  
    	MinaClient client = new MinaClient();
    	client.iconnect();
    	
    	for(int i=0;i<10;i++)
    	{
    		client.send("我是mina :" +i);
    		Thread.sleep(2000);
    	}
    	
    	client.close();
    }  
    
    public boolean iconnect()
    {
        start = System.currentTimeMillis();  
        //Create TCP/IP connection 
        connector = new NioSocketConnector(); 
        //创建接受数据的过滤器     
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();   
        chain.addLast("codec", new ProtocolCodecFilter(new MsgCodecFactory(Charset.forName("UTF-8"))));  
        
        //客户端的消息处理器：一个MinaClentHander对象   
        connector.setHandler(new MinaClientHandlerAdapter()); 
        //Buffer 大小
        connector.getSessionConfig().setReadBufferSize(100);  
        connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 1000); //10秒
         
        //连接到服务器：
        connFuture = connector.connect(new InetSocketAddress(sHost, sPort));  
        //listener 查看连接是否断开  
        // 等待连接创建完成 
        connFuture.awaitUninterruptibly(); 
        // 获取当前session 
        if(connFuture.isConnected())
        {
        	session = connFuture.getSession();
        	cfuture = session.getCloseFuture();
        }
        System.out.println("start client ...");  
        
        return true;
    }
    
    public void setAttribute(Object key, Object value) { 
        session.setAttribute(key, value); 
    } 

    public void send(String message) {   
    	try {   
    		if(connFuture.isConnected())
    		{ 
    			MsgEntity msg = new MsgEntity(message);
	    		session.write(msg); 
	    		System.out.println("send message " + message);  
    		} else
    		   System.out.println("out connect ");  
        } catch (RuntimeIoException e) {  
            if (e.getCause() instanceof ConnectException) {  
                try {  
                    if (connFuture.isConnected()) {  
                    	connFuture.getSession().close(true);  
                    }  
                } catch (RuntimeIoException e1) {  
                }  
            }  
        }  
        
    } 
    
    public void send(byte[] message) {   
    	try {   
    		if(connFuture.isConnected())
    		{ 
    			MsgEntity msg = new MsgEntity(message);
	    		session.write(msg); 
	    		System.out.println("send message " + message.length);  
    		} else
    		   System.out.println("out connect ");  
        } catch (RuntimeIoException e) {  
            if (e.getCause() instanceof ConnectException) {  
                try {  
                    if (connFuture.isConnected()) {  
                    	connFuture.getSession().close(true);  
                    }  
                } catch (RuntimeIoException e1) {  
                }  
            }  
        }  
        
    } 

    public boolean close() { 
    	if(cfuture != null)
    		cfuture.awaitUninterruptibly(1000);  
        connector.dispose(); 
        return true; 
    } 

    public IoConnector getConnector() { 
        return connector; 
    } 

    public IoSession getSession() { 
        return session;  
    }

	@Override
	public void setPort(int port) {
		this.sPort = port;
	}

	@Override
	public void setHost(String hostip) {
		this.sHost = hostip;		
	}  
}  
